﻿using BLL;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Microsoft.Office.Interop.Excel;
using Model;
using NPOI.Util;
using SQLHelper;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.BLL;
using 后整理管理系统.入库管理;
using 后整理管理系统.其他窗体;
using 后整理管理系统.数据分析;
using 后整理管理系统.新增窗体;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.新增窗体;
using 纺织贸易管理系统.设置窗体;
using 纺织贸易管理系统.选择窗体;

namespace 纺织贸易管理系统.报表窗体
{
    public partial class 来货入库 : Form
    {
        public 来货入库()
        {
            InitializeComponent();
            uiDatePicker2.Value = DateTime.Now.Date.AddDays(1).AddSeconds(-1);
            uiDatePicker1.Value = uiDatePicker2.Value.AddDays(-QueryTime.间隔);
            CreateGrid.Create(this.Name, gridView1);
           // gridView1.Columns["UpRolledNum"].OptionsColumn.AllowEdit = AccessBLL.CheckAccess("上卷米数");
            gridView1.Columns["rq"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";//设置时间显示格式
            //gridView1.Columns["chengpingmishu"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom ;
            gridView1.Columns["chengpingmishu"].DisplayFormat.FormatString = "F0";
            gridView1.Columns["chengpingjuanshu"].DisplayFormat.FormatString = "N0";
            gridView1.OptionsCustomization.AllowSort = true;
            //gridView1.OptionsBehavior.Editable = false;
            query();
        }

        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AccessBLL.CheckAccess("新增来货入库单"))
            {
                MainForm.mainform.AddMidForm(new 来货入库单() { Useful = FormUseful.新增 });
            }
        }
        private void query()
        {
            try
            {
                uiDatePicker2.Value = uiDatePicker2.Value.Date.AddDays(1).AddSeconds(-1);
                
                var db = Connect.dbcontext;

                var query = db.Queryable<DanjuTable,danjumingxitable>((x,y)=>x.dh==y.danhao)
                     .Where((x, y) =>
                     x.rq >= uiDatePicker1.Value.Date &&
                      x.rq <= uiDatePicker2.Value.Date.AddDays(1) &&
                      x.ksmc.Contains(txtkehu.Text) &&
                     y.pingming.Contains(txtpingming.Text) &&
                     y.OrderNum.Contains(txtOrdernum.Text )&&
                     y.ganghao.Contains(txtganghao.Text )&&
                     y.yanse.Contains(txtyanse.Text )&&
                       // 其他条件类似处理...
                     x.djlx==DanjuLeiXing.入库单)
                     .OrderByDescending(x => x.rq);
                var dt = query.Select((x,y) => new {
                    x.id,
                ID1= y.ID,y.pingming,x.dh,x.bz,x.ksmc,x.ckmc,y.CustomName,x.own,x.jiagongleixing,x.fromDanhao,y.kezhong,
                    toupimishu1=y.toupimishu,
                    y.danwei,y.Bianhao,
                    toupijuanshu1=y.toupijuanshu,y.ExitsNum,y.ExitsRoll,y.Kuwei,y.Rangchang,y.offerid,y.danhao,
                   y.ganghao,y.yanse,y.beizhu,OrderNum1= y.OrderNum,y.houzhengli,suolv1=y.suolv,y.UpRolledNum,y.UpRolledRolls,y.InventoryQuantity,
                   y.kuanhao,
                   y.OutboundUnit,y.ProducedQuantity,y.chengpingmishu,y.chengpingjuanshu,y.FabricStyle,y.RollUpShrinkageRate,x.rq,x.Fahuodizhi
                }).ToDataTable();
                gridControl1.DataSource = dt;
            }
            catch(Exception ex)
            {
                ShowMessageBox.ShowErrorBox (ex.Message);
            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            query();
        }

        private void 来货入库_Load(object sender, EventArgs e)
        {
        }

        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AccessBLL.CheckAccess("修改来货入库单"))
            {
                if (gridView1.FocusedRowHandle >= 0)
                {
                    var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
                    var mingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danhao);
                    if (Connect.dbcontext.Queryable<StockTable>().Where(x => x.RKDH == danhao && !string.IsNullOrWhiteSpace(x.LiuzhuanCard)).Count() > 0)
                    {
                        if (Tools.ShowMessageBox.ShowAskBox("该入库单号存在开卡记录！\r\n是否继续修改") == DialogResult.No)
                        {
                            return;
                        }
                    }
                    if (mingxis.Where(x => x.toupimishu > 0).ToList().Count >= 1)
                    {
                        if (Sunny.UI.UIMessageBox.ShowAsk("该入库单已经存在发货记录！\r\n是否继续修改"))
                        {
                            MainForm.mainform.AddMidForm(new 来货入库单() { Useful = FormUseful.修改, danju = DanjuTableService.GetOneDanjuTable(x => x.dh == danhao) });
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        MainForm.mainform.AddMidForm(new 来货入库单() { Useful = FormUseful.修改, danju = DanjuTableService.GetOneDanjuTable(x => x.dh == danhao) });
                    }

                }
                else
                {
                    Sunny.UI.UIMessageBox.ShowError("没有任何内容被选中!");
                }
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AccessBLL.CheckAccess("删除来货入库单"))
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();

                if (Sunny.UI.UIMessageBox.ShowAsk($"您确定要删除{danhao}该来货登记单吗?") == true)
                {
                    if (Connect.dbcontext.Queryable<JuanHaoTable>().Where(x => x.ReceiptNo == danhao).Any())
                    {
                        Sunny.UI.UIMessageBox.ShowError($"该来货入库单号{danhao}已经存在打卷记录！\r\n请先删除打卷记录");
                        return;
                    }
                    if (! Connect.dbcontext.Queryable<DanjuTable>().Any(x => x.dh == danhao))
                    {
                        ShowMessageBox.ShowErrorBox("该单号已经不存在了！删除失败");
                        return;
                    }
                    if (new GetIDHelper().GetSelectDanjumingxi(SelectHelper.GetSelect(gridView1)).Where(x => x.InventoryQuantity == 0).Count() > 0)
                    {
                        ShowMessageBox.ShowErrorBox("检查到有布料已经发完货了!不能删除");
                        return;
                    }
                    if (Connect.dbcontext.Queryable<StockTable>().Any(x => x. RKDH== danhao && x.LiuzhuanCard != string.Empty))
                    {
                        ShowMessageBox.ShowErrorBox("该单据已经开具流转卡!不能删除");
                        return;
                    }
                    try
                    {
                        using (var trans = Connect.dbcontext.UseTran())
                        {
                            //if (StockTableService.GetStockTablelst(x => x.RKDH == danhao && x.LiuzhuanCard != string.Empty).Count > 0)
                            //{
                            //    if (Sunny.UI.UIMessageBox.ShowAsk("该单据已经开具流转卡！\r\n删除单据将把流转卡一起删除！\r\n确定要删除改单据吗？"))
                            //    {
                            //        var danjumingxis = Connect.dbcontext.Queryable<danjumingxitable>().Where(x => x.danhao == danhao).ToList();
                            //        foreach (var item in danjumingxis.Where(x => !string.IsNullOrEmpty(x.offerid)).Select(x => x.offerid))
                            //        {
                            //            流转单BLL.删除流转卡(item);
                            //        }
                            //    }
                            //    else
                            //    {
                            //        trans.RollbackTran();
                            //        return;
                            //    }
                            //}
                            生产入库单BLL.Delete(danhao);
                            Connect.dbcontext.Insertable(new DeleteLog() { date = DateTime.Now, Log = $"删除生产入库单{danhao}", useID = Tools.CurrentUser.user.YHBH }).ExecuteCommand();
                            trans.CommitTran();
                            AlterDlg.Show("删除成功");
                            query();
                        }
                    }
                    catch (Exception ex)
                    {
                        Sunny.UI.UIMessageBox.ShowError("删除失败！原因是：" + ex.Message);
                    }
                }
            }
        }

        private void 导出到EXCELToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AccessBLL.CheckAccess("导出来货入库单"))
            {
                try
                {
 
                    ExportFile.导出到文件(gridControl1, "生产入库清单");
                }
                catch (Exception ex)
                {
                    ShowMessageBox.ShowErrorBox(ex.Message);
                }
               
            }
        }

        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView1) { formname = this.Name, Obj = null, dt = gridControl1.DataSource as System.Data.DataTable };
            fm.ShowDialog();
            //gridView1.Columns["UpRolledNum"].OptionsColumn.AllowEdit = AccessBLL.CheckAccess("上卷米数");
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView1);
        }
        private void 入库日报表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm.mainform.AddMidForm(new 进仓日报表());
        }

        private void 入库月报表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm.mainform.AddMidForm(new 进仓月报表());
        }

        private void 复制单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridControl1.Focus();
            SendKeys.Send("^c");
        }

        private void txtganghao_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter )
            {
                query();
            }
        }

        private void 出库信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
                var ganghao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ganghao").ToString();
                var yanse = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "yanse").ToString();
                var xiaoshoumingxi = danjumingxitableService.Getdanjumingxitablelst(x => x.rkdh == danhao&&x.yanse==yanse&&x.ganghao==ganghao);
                if(xiaoshoumingxi.Count >0)
                {
                    var saledanhao = xiaoshoumingxi[0];
                    new 出库信息() { Danhao = danhao, LotNo = xiaoshoumingxi[0].ganghao }.ShowDialog();
                }
            }
            else
            {
                Sunny.UI.UIMessageBox.ShowError("没有任何内容被选中!");
            }
        }

        private void 查看入库细码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
               var FineCodeTable = new System.Data.DataTable();
                var detaicodelist = Connect.CreatConnect().Query<WarehousingDetailCode>(x => x.DocNum == danhao);
                foreach (var col in detaicodelist.Select(x => x.LotNum).Distinct())
                {
                    int rowindex = 0;
                    FineCodeTable.Columns.Add(col);
                    foreach (var d in detaicodelist.Where(x => x.LotNum == col).ToList())
                    {
                        if (rowindex == FineCodeTable.Rows.Count)
                        {
                            FineCodeTable.Rows.Add();
                        }
                        FineCodeTable.Rows[rowindex][col] = d.Length;
                        rowindex++;
                    }
                }
                var fm = new 输入来货细码()
                {
                    useful = FormUseful.修改,
                    dt = FineCodeTable,
                    mingxilist = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danhao)
                };
                fm.ShowDialog();
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                var ID1 = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID1").ToString();
                //修改上卷米数
                switch (gridView1.FocusedColumn.FieldName)
                {
                    case "UpRolledNum":
                        if (AccessBLL.CheckAccess("上卷米数"))
                        {

                            Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.UpRolledNum == (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "UpRolledNum")).ExecuteCommand();
                        }
                        else
                        {
                            ShowMessageBox.ShowErrorBox("您没有权限修改上卷米数");
                            gridView1.Columns["UpRolledNum"].OptionsColumn.AllowEdit = false;
                        }
                        break;
                    case "beizhu":
                        Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.beizhu == (string)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "beizhu")).ExecuteCommand();
                        break;
                    case "ExitsNum":
                        if (AccessBLL.CheckAccess("修改退仓米数"))
                        {
                            var d = Connect.dbcontext.Queryable<danjumingxitable>().First(x => x.ID == ID1.ToInt(0));
                            if (d != null)
                            {
                                d.ExitsNum = (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ExitsNum");
                                if (d.InventoryQuantity != 0)
                                {
                                    d.InventoryQuantity = d.chengpingmishu - d.toupimishu - d.ExitsNum;
                                    if (d.InventoryQuantity < 0)
                                    {
                                        d.InventoryQuantity = 0;
                                    }
                                }
                                销售发货单BLL.CalculateShrinkage(d);
                                Connect.dbcontext.Updateable(d).ExecuteCommand();
                                query();
                            }
                            //Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.ExitsNum == (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ExitsNum")).ExecuteCommand();
                        }
                        else
                        {
                            ShowMessageBox.ShowErrorBox("您没有权限修改退仓米数");
                            gridView1.Columns["ExitsNum"].OptionsColumn.AllowEdit = false;
                        }
                        break;
                    case "ExitsRoll":
                        if (AccessBLL.CheckAccess("修改退仓卷数"))
                        {

                            Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.ExitsRoll == (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ExitsRoll")).ExecuteCommand();
                        }
                        else
                        {
                            ShowMessageBox.ShowErrorBox("您没有权限修改退仓卷数");
                            gridView1.Columns["ExitsRoll"].OptionsColumn.AllowEdit = false;
                        }
                        break;
                    case "UpRolledRolls":
                        if (AccessBLL.CheckAccess("上卷卷数"))
                        {

                            Connect.dbcontext.Updateable<danjumingxitable>().Where(x => x.ID == ID1.ToInt(0)).SetColumns(x => x.UpRolledRolls == (decimal)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "UpRolledRolls")).ExecuteCommand();
                        }
                        else
                        {
                            gridView1.Columns["UpRolledNum"].OptionsColumn.AllowEdit = false;
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox(ex.Message);
            }

        }

        private void 生成出库单ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                if (AccessBLL.CheckAccess("新增销售出库单"))
                {
                    if (gridView1.GetSelectedRows().Length == 0)
                    {
                        Tools.ShowMessageBox.ShowErrorBox("没有任何布料被选中！\r\n生成失败");
                        return;
                    }
                    var stocks = new List<StockTable>();
                    foreach (DataRow r in SelectHelper.GetSelect(gridView1).Rows)
                    {
                        var mingxi = danjumingxitableService.GetOnedanjumingxitable(x => x.ID == (int)r["ID1"]);

                        var liuzhuanka = Connect.dbcontext.Queryable<Liuzhuancard>().First(x => x.CardNum == mingxi.offerid);
                        var stockcolor = string.Empty;
                        //if (liuzhuanka != null)
                        //{
                        //    stockcolor = string.IsNullOrEmpty(liuzhuanka.BaseFabricColor) ? mingxi.yanse : mingxi.yanse + "/" + liuzhuanka.BaseFabricColor;
                        //}
                        //else
                        //{
                            stockcolor = mingxi.yanse;
                        //}
                        var inventorys = Connect.dbcontext.Queryable<StockTable>().Where(x => x.RKDH == mingxi.danhao && x.YS == stockcolor && x.GH == mingxi.ganghao && x.PM == mingxi.pingming).ToList();
                        if (inventorys.Count > 1)
                        {
                            var fm = new 库存选择(mingxi.ganghao, stockcolor, mingxi.pingming) { CustomerName = inventorys[0].CustomName, Danhao = inventorys[0].RKDH };
                            fm.ShowDialog();
                            stocks.AddRange(fm.pingzhong);
                        }
                        else
                        {
                            if (inventorys.Count == 0)
                            {
                                //已经出库的信息不能再次出库
                                Tools.ShowMessageBox.ShowErrorBox("生成发货单的时候检查到库存信息已经没有的布料！\r\n缸号是" + mingxi.ganghao + "\r\n生成失败");
                                return;
                            }
                            else
                            {
                                if (inventorys.Count == 1)
                                {
                                    stocks.AddRange(inventorys);
                                }
                            }
                        }
                    }
                    ///不同客户不允许开单
                    if (stocks.Select(x => x.CustomName).Distinct().Count() > 1)
                    {
                        Tools.ShowMessageBox.ShowErrorBox("所选布料归属为两个或两个以上客户！\r\n生成失败");
                        return;
                    }
                    MainForm.mainform.AddMidForm(new 销售发货单() { stockTables = stocks, useful = FormUseful.新增 });
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("创建发货单的时候发送了错误:" + ex.Message);
            }
       
        }

        private void 查看开卡信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var mingxi = Connect.dbcontext.Queryable<danjumingxitable>().First(x => x.ID== (int)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID1"));
                if (mingxi != null)
                {
                    new 查看开卡信息() { LotNo = mingxi.ganghao, DocNum = mingxi.danhao }.ShowDialog();
                }
            }
            catch(Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("查看开卡信息的时候的发生了错误:" + ex.Message);

            }
        }

        private void 流转卡ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (AccessBLL.CheckAccess("新增流转卡"))
                {
                    var selectdt = SelectHelper.GetSelect(gridView1);
                    if (selectdt.Rows.Count == 0)
                    {
                        this.ShowErrorDialog("没有任何布料被选中！请在布料前面打上勾");
                        return;
                    }
                    var idstring = new GetIDHelper().GetDanjumingxiID(selectdt);
                    if (!string.IsNullOrEmpty(idstring))
                    {
                        var mingxis = Connect.dbcontext.Ado.SqlQuery<danjumingxitable>($"select * from danjumingxitable where id in ({idstring})");
                        //if (mingxis.FirstOrDefault(x => x.ProducedQuantity == x.chengpingmishu)== null)
                        //{
                        var danjus = Connect.dbcontext.Ado.SqlQuery<DanjuTable>($"select * from danjutable where dh in (select danhao from danjumingxitable where danjumingxitable.id in ({idstring})) ");
                        if (danjus.Select(x => x.ksmc).Distinct().Count() > 2)
                        {
                            ShowMessageBox.ShowErrorBox("下推流转卡的时候发生了错误：所选择的布料属于2个或及以上的客户！");
                            return;
                        }
                        else
                        {
                            var danju = danjus[0];
                            if (new GetIDHelper().GetSelectDanjumingxi(selectdt).Where(x => x.InventoryQuantity == 0).Count() > 0)
                            {
                                ShowMessageBox.ShowErrorBox("检查到有布料已经发完货了!不能开生产卡了");
                                return;
                            }
                            else
                            {
                                MainForm.mainform.AddMidForm(new 流转卡() { danjumingxis = mingxis, Useful = FormUseful.复制, danju = danju });
                            }

                        }
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox("下推流转卡的时候发生了错误：" + ex.Message);
            }
         }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "dh").ToString();
                MainForm.mainform.AddMidForm(new 来货入库单() { Useful = FormUseful.查看, danju = DanjuTableService.GetOneDanjuTable(x => x.dh == danhao) });
            }
        }

        private void 查看流转卡ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var danhao = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "offerid").ToString();
                if (!string.IsNullOrEmpty(danhao))
                {
                    MainForm.mainform.AddMidForm(new 流转卡() { Useful = FormUseful.查看, liuzhuancard = LiuzhuancardService.GetOneLiuzhuancard(x => x.CardNum == danhao) });
                }
                else
                {
                    this.ShowErrorDialog("该布料还没有开具流转卡");
                }
            }
            else
            {
                Sunny.UI.UIMessageBox.ShowError("没有任何内容被选中!");
            }
        }

        private void 生产补卡ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var selectdt = SelectHelper.GetSelect(gridView1);
                if (selectdt.Rows.Count == 0)
                {
                    this.ShowErrorDialog("没有任何布料被选中！请在布料前面打上勾");
                    return;
                }
                var idstring = new GetIDHelper().GetDanjumingxiID(selectdt);
                if (!string.IsNullOrEmpty(idstring))
                {
                    var mingxis = Connect.dbcontext.Ado.SqlQuery<danjumingxitable>($"select * from danjumingxitable where id in ({idstring})");
                    //if (mingxis.FirstOrDefault(x => x.ProducedQuantity == x.chengpingmishu)== null)
                    //{
                    var danjus = Connect.dbcontext.Ado.SqlQuery<DanjuTable>($"select * from danjutable where dh in (select danhao from danjumingxitable where danjumingxitable.id in ({idstring})) ");
                    if (danjus.Select(x => x.ksmc).Distinct().Count() > 2)
                    {
                        ShowMessageBox.ShowErrorBox("下推流转卡的时候发生了错误：所选择的布料属于2个或及以上的客户！");
                        return;
                    }
                    else
                    {
                        if (mingxis.Select(x => x.offerid).Distinct().Count() >= 2)
                        {
                            ShowMessageBox.ShowErrorBox("下推流转卡的时候发生了错误：选中的明细归属在两张不通的流转卡上！");
                            return;
                        }

                        if (mingxis.Count > 0)
                        {
                            MainForm.mainform.AddMidForm(new 流转卡() { danjumingxis = mingxis, Useful = FormUseful.查看, liuzhuancard = LiuzhuancardService.GetOneLiuzhuancard(x => x.CardNum == mingxis[0].offerid) });
                        }

                    }
                    //}
                    //else
                    //{
                    //    if (this.ShowAskDialog( "选中的布料已经没有可以开卡的数量了！\r\n是否修改之前的流转卡"))
                    //    {
                    //        if (mingxis.Where(x => !string.IsNullOrEmpty(x.offerid)).Select(x => x.offerid).Distinct().Count() > 1)
                    //        {
                    //            ShowMessageBox.ShowErrorBox("所选的布料归属两个不同的流转卡！不能进行下推动作！");
                    //            return;
                    //        }
                    //        else
                    //        {
                    //            MainForm.mainform.AddMidForm(new 流转卡() { Useful = FormUseful.修改, liuzhuancard = LiuzhuancardService.GetOneLiuzhuancard(x => x.CardNum == mingxis[0].offerid) });
                    //        }
                    //    }
                    //}
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox("下推流转卡的时候发生了错误：" + ex.Message);
            }
        }

        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            // 假设我们基于某个条件来设置颜色
            if (e.RowHandle >= 0 && e.RowHandle < gridView1.DataRowCount)
            {
                // 获取当前行的数据
                DataRow row = gridView1.GetDataRow(e.RowHandle);
                // 假设我们根据某个字段的值来设置颜色
                //string someFieldValue = row["InventoryQuantity"].ToString();
                //if (row["Rangchang"].ToString() == "退卷")
                //{
                //    //e.Appearance.BackColor = Color.Red; // 设置背景色
                //    e.Appearance.cell.ForeColor = Color.DarkBlue;
                //}
                //if (row["Rangchang"].ToString() == "上机")
                //{
                //    //e.Appearance.BackColor = Color.Red; // 设置背景色
                //    e.Appearance.ForeColor = Color.WhiteSmoke;
                //}
                //if (row["Rangchang"].ToString() == "下机")
                //{
                //    //e.Appearance.BackColor = Color.Red; // 设置背景色
                //    e.Appearance.ForeColor = Color.NavajoWhite;
                //}
                //if (row["Rangchang"].ToString() == "翻卷")
                //{
                //    //e.Appearance.BackColor = Color.Red; // 设置背景色
                //    e.Appearance.ForeColor = Color.Silver;
                //}
                // 设置背景色和字体色
                if (row.Table.Columns.Contains("InventoryQuantity"))
                {
                    if (row["InventoryQuantity"].ObjToDecimal() == 0)
                    {
                        //e.Appearance.BackColor = Color.Red; // 设置背景色
                        e.Appearance.ForeColor = Color.Red;
                    }
                }
            }
        }

        private void 查看测试结果ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var row=gridView1.GetFocusedRow() as DataRowView;
                try
                {
                    var danhao = row.Row["danhao"].ToString();
                    var fm = new 测试结果(new TestData() { DocNum = danhao, Color = row.Row["yanse"].ToString(),LotNo = row.Row["ganghao"] .ToString()
                        ,FabricName= row.Row["pingming"].ToString()
                    });
                    fm.ShowDialog();
                }
                catch(Exception ex)
                {
                    ShowMessageBox.ShowErrorBox(ex.Message);
                }
            }
        }

        private void 查看排产ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var row = gridView1.GetFocusedRow() as DataRowView;
                try
                {
                    var danhao = row.Row["offerid"].ToString();
                    var fm = new 工艺二次登记(Connect.dbcontext.Queryable<Liuzhuancard>().Where(x => x.CardNum == danhao).ToList(), FormUseful.查看, new ScheduleDoc());
                    fm.ShowDialog();
                }
                catch (Exception ex)
                {
                    ShowMessageBox.ShowErrorBox(ex.Message);
                }
            }
        }

        private void 查看细码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectdt = SelectHelper.GetSelect(gridView1);
            var idstring = new GetIDHelper().GetDanjumingxiID(selectdt);
            if (!string.IsNullOrEmpty(idstring))
            {
                var mingxis = Connect.dbcontext.Ado.SqlQuery<danjumingxitable>($"select * from danjumingxitable where id in ({idstring})");
                var fm=new 查看细码(mingxis);
                fm.ShowDialog();
            }
        }

        private void 查看生产进度ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var row = gridView1.GetFocusedRow() as DataRowView;
                try
                {
                    var danhao = row.Row["offerid"].ToString();
                    var fm = new 生产进度 (danhao);
                    fm.ShowDialog();
                }
                catch (Exception ex)
                {
                    ShowMessageBox.ShowErrorBox(ex.Message);
                }
            }
        }

        private void 生产退仓单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (AccessBLL.CheckAccess("新增来货退卷单"))
                {
                    if (gridView1.GetSelectedRows().Length == 0)
                    {
                        Tools.ShowMessageBox.ShowErrorBox("没有任何布料被选中！\r\n生成失败");
                        return;
                    }
                    var stocks = new List<StockTable>();
                    foreach (DataRow r in SelectHelper.GetSelect(gridView1).Rows)
                    {
                        var mingxi = danjumingxitableService.GetOnedanjumingxitable(x => x.ID == (int)r["ID1"]);

                        var liuzhuanka = Connect.dbcontext.Queryable<Liuzhuancard>().First(x => x.CardNum == mingxi.offerid);
                        var stockcolor = string.Empty;
                        //if (liuzhuanka != null)
                        //{
                        //    stockcolor = string.IsNullOrEmpty(liuzhuanka.BaseFabricColor) ? mingxi.yanse : mingxi.yanse + "/" + liuzhuanka.BaseFabricColor;
                        //}
                        //else
                        //{
                        stockcolor = mingxi.yanse;
                        //}
                        var inventorys = Connect.dbcontext.Queryable<StockTable>().Where(x => x.RKDH == mingxi.danhao
                        && x.YS == stockcolor
                        &&x.orderNum==mingxi.OrderNum
                        && x.GH == mingxi.ganghao && x.PM == mingxi.pingming).ToList();
                        if (inventorys.Count > 1)
                        {
                            var fm = new 库存选择(mingxi.ganghao, stockcolor, mingxi.pingming) { CustomerName = inventorys[0].CustomName, Danhao = inventorys[0].RKDH };
                            fm.ShowDialog();
                            stocks.AddRange(fm.pingzhong);
                        }
                        else
                        {
                            if (inventorys.Count == 0)
                            {
                                //已经出库的信息不能再次出库
                                Tools.ShowMessageBox.ShowErrorBox("生成发货单的时候检查到库存信息已经没有的布料！\r\n缸号是" + mingxi.ganghao + "\r\n生成失败");
                                return;
                            }
                            else
                            {
                                if (inventorys.Count == 1)
                                {
                                    stocks.AddRange(inventorys);
                                }
                            }
                        }
                    }
                    ///不同客户不允许开单
                    if (stocks.Select(x => x.CustomName).Distinct().Count() > 1)
                    {
                        Tools.ShowMessageBox.ShowErrorBox("所选布料归属为两个或两个以上客户！\r\n生成失败");
                        return;
                    }
                    MainForm.mainform.AddMidForm(new 来货退仓单() { stockTables = stocks, Useful = FormUseful.新增 });
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("创建退货单的时候发送了错误:" + ex.Message);
            }
        }
        private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (view == null || e.RowHandle < 0) return;

            // 仅处理Rangchang列
            if (e.Column.FieldName == "Rangchang")
            {
                object cellValue = view.GetRowCellValue(e.RowHandle, "Rangchang");

                // 条件判断示例
                if (cellValue != null)
                {
                    string value = cellValue.ToString();
                    if (value == "退卷")
                    {
                        e.Appearance.BackColor = Color.Orange;
                        e.Appearance.ForeColor = Color.Black;
                    }
                    else if (value == "下机")
                    {
                        e.Appearance.BackColor = Color.Red;
                        e.Appearance.ForeColor = Color.White;
                    }
                    else if (value == "上机")
                    {
                        e.Appearance.BackColor = Color.Green;
                        e.Appearance.ForeColor = Color.White;
                    }
                }
            }
        }

        private void 回填信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var ID1 = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID1").TryToInt();
               var mingxi = danjumingxitableService.GetOnedanjumingxitable(x => x.ID == ID1);
                if (mingxi == null)
                {
                    ShowMessageBox.ShowErrorBox("没有找到该明细信息！");
                    return;
                }
                var fm = new 回填信息() { Mingxi = mingxi };
                fm.ShowDialog();
                query();
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox("回填信息的时候发生了错误：" + ex.Message);
            }
        }
    }
}
